<template>
  <div class="template-management-container">
    <!-- 头部标题和新增按钮 -->
    <div class="header">
      <span class="title">信息管理</span>
      <el-button type="primary" @click="showAddDialog">新增定时消息</el-button>
    </div>

    <!-- 查询条件卡片 -->
    <el-card class="search-card">
      <el-form :model="searchForm" :inline="true">
        <el-form-item label="模板名称：">
          <el-input
              v-model="searchForm.name"
              placeholder="请输入模板名称"
              clearable
              @keydown.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="模板状态" style="width:290px;">
          <el-select placeholder="请选择模板状态" v-model="searchForm.status" @change="loadCategories">
            <el-option label="全部" value="" />
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 模板列表表格 -->
    <el-card class="table-card">
      <el-table :data="templateList" stripe border>
        <el-table-column
            prop="id"
            label="序号"
            width="80"
            align="center"
        />
        <el-table-column
            prop="name"
            label="模板名称"
            align="center"
            width="180"
        />
        <el-table-column
            prop="title"
            label="消息标题"
            align="center"
            show-overflow-tooltip
        />
        <el-table-column
            prop="activity"
            label="营销活动"
            align="center"
            width="180"
        >
          <template #default="{ row }">
            <el-tag v-if="row.activity" type="info">{{ row.activity }}</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column
            prop="createTime"
            label="创建时间"
            align="center"
            width="180"
        />
        <el-table-column
            prop="status"
            label="启用状态"
            align="center"
            width="120"
        >
          <template #default="{ row }">
            <el-switch
                v-model="row.status"
                active-value="1"
                inactive-value="0"
                @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column
            label="操作"
            align="center"
            width="150"
        >
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          class="pagination"
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
      />
    </el-card>

    <!-- 新增/编辑模板对话框 -->
    <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="50%"
        :before-close="handleClose"
    >
      <el-form
          :model="templateForm"
          label-width="120px"
          label-position="top"
          ref="templateFormRef"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="模板名称" prop="name" required>
              <el-input v-model="templateForm.name" placeholder="请输入模板名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="消息标题" prop="title" required>
              <el-input v-model="templateForm.title" placeholder="请输入消息标题" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="消息内容" prop="content" required>
              <el-input
                  v-model="templateForm.content"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入消息内容"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="关联活动" prop="activity">
              <el-button type="primary" @click="showActivityDialog">选择活动</el-button>
              <span v-if="templateForm.activity" style="margin-left: 10px;">
                {{ templateForm.activity }}
              </span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="启用状态" prop="status">
              <el-radio-group v-model="templateForm.status">
                <el-radio border label="1">启用</el-radio>
                <el-radio border label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitTemplate">确定</el-button>
      </template>
    </el-dialog>

    <!-- 选择活动对话框 -->
    <el-dialog
        title="选择活动"
        v-model="activityDialogVisible"
        width="60%"
    >
      <el-form :inline="true">
        <el-form-item label="活动名称：">
          <el-input v-model="activitySearch.name" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="活动类型" style="width:290px;">
          <el-select placeholder="请选择活动类型" v-model="searchForm.status" @change="loadCategories">
            <el-option label="全部" value="" />
            <el-option label="促销" value="promotion" />
            <el-option label="节日" value="festival" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchActivity">查询</el-button>
        </el-form-item>
      </el-form>
      <el-table
          :data="activityList"
          border
          @selection-change="handleActivitySelection"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="id" label="序号" width="80" align="center" />
        <el-table-column prop="name" label="活动名称" align="center" />
        <el-table-column prop="target" label="活动目标" align="center" />
        <el-table-column prop="type" label="活动类型" align="center" />
        <el-table-column prop="channel" label="推广渠道" align="center" />
        <el-table-column prop="time" label="活动时间" align="center" width="220" />
      </el-table>
      <template #footer>
        <el-button @click="activityDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="selectActivity">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索表单
const searchForm = reactive({
  name: '',
  status: ''
})

// 模板列表数据
const templateList = ref([
  {
    id: '59',
    name: '消息模板',
    title: '快乐双十一',
    activity: '欢乐点赞样式活动',
    createTime: '2004-06-06 01:71:6',
    status: '1'
  },
  {
    id: '58',
    name: '定时消息模板',
    title: '欢乐点赞样式活动',
    activity: '欢乐点赞样式活动',
    createTime: '2004-06-06 03:34:3',
    status: '0'
  },
  {
    id: '57',
    name: '文件消息模板',
    title: '快手双十一',
    activity: '欢乐点菜单',
    createTime: '2024-06-06 10:17:16',
    status: '1'
  },
  {
    id: '56',
    name: '定时消息模板',
    title: '欢乐点菜单',
    activity: '',
    createTime: '2024-06-06 09:53:03',
    status: '0'
  }
])

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 4
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('新增定时消息')
const templateForm = reactive({
  id: '',
  name: '',
  title: '',
  content: '',
  activity: '',
  status: '1'
})
const templateFormRef = ref(null)

// 活动选择相关
const activityDialogVisible = ref(false)
const activitySearch = reactive({
  name: '',
  type: ''
})
const activityList = ref([
  {
    id: '34',
    name: '欢乐谷周年庆活动',
    target: '欢乐谷周年庆送券',
    type: '全部',
    channel: 'APP',
    time: '2024-06-05 - 2024-06-30'
  },
  {
    id: '35',
    name: '水立方周年庆活动',
    target: '欢乐谷周年庆送券',
    type: '全部',
    channel: 'APP',
    time: '2024-06-05 - 2024-06-30'
  }
])
const selectedActivity = ref(null)

// 状态变更
const handleStatusChange = (row) => {
  console.log(`模板 ${row.name} 状态变更为: ${row.status === '1' ? '启用' : '禁用'}`)
  // 这里可以添加API调用
  ElMessage.success('状态更新成功')
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  // 这里可以添加API调用
  console.log('搜索条件:', searchForm)
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.status = ''
  handleSearch()
}

// 显示新增对话框
const showAddDialog = () => {
  dialogTitle.value = '新增定时消息'
  Object.assign(templateForm, {
    id: '',
    name: '',
    title: '',
    content: '',
    activity: '',
    status: '1'
  })
  dialogVisible.value = true
}

// 编辑模板
const handleEdit = (row) => {
  dialogTitle.value = '编辑定时消息'
  Object.assign(templateForm, {
    id: row.id,
    name: row.name,
    title: row.title,
    content: '',
    activity: row.activity,
    status: row.status
  })
  dialogVisible.value = true
}

// 删除模板
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除模板 "${row.name}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 这里添加删除API调用
    templateList.value = templateList.value.filter(item => item.id !== row.id)
    pagination.total -= 1
    ElMessage.success('删除成功')
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 提交模板表单
const submitTemplate = () => {
  templateFormRef.value.validate((valid) => {
    if (!valid) return

    if (dialogTitle.value === '新增定时消息') {
      // 新增逻辑
      const newTemplate = {
        id: Date.now().toString(),
        name: templateForm.name,
        title: templateForm.title,
        activity: templateForm.activity,
        createTime: new Date().toLocaleString(),
        status: templateForm.status
      }
      templateList.value.unshift(newTemplate)
      pagination.total += 1
      ElMessage.success('新增成功')
    } else {
      // 编辑逻辑
      const index = templateList.value.findIndex(item => item.id === templateForm.id)
      if (index !== -1) {
        templateList.value[index].name = templateForm.name
        templateList.value[index].title = templateForm.title
        templateList.value[index].activity = templateForm.activity
        templateList.value[index].status = templateForm.status
        ElMessage.success('修改成功')
      }
    }
    dialogVisible.value = false
  })
}

// 关闭对话框
const handleClose = () => {
  templateFormRef.value?.resetFields()
  dialogVisible.value = false
}

// 显示活动选择对话框
const showActivityDialog = () => {
  activityDialogVisible.value = true
}

// 活动选择变化
const handleActivitySelection = (selection) => {
  selectedActivity.value = selection.length > 0 ? selection[0] : null
}

// 选择活动
const selectActivity = () => {
  if (selectedActivity.value) {
    templateForm.activity = selectedActivity.value.name
    activityDialogVisible.value = false
  } else {
    ElMessage.warning('请选择一个活动')
  }
}

// 搜索活动
const searchActivity = () => {
  // 这里可以添加活动搜索API调用
  console.log('活动搜索条件:', activitySearch)
}

// 分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  // 这里可以添加数据重新加载逻辑
}

// 页码变化
const handlePageChange = (val) => {
  pagination.currentPage = val
  // 这里可以添加数据重新加载逻辑
}
</script>

<style scoped>
.template-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  height: 100%;
}

.header {
  height: 60px;
  background-color: #fff;
  padding: 10px 20px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header .title {
  font-size: 20px;
  line-height: 40px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>